// Lore Server runs at port no. 2046
import java.io.*;
import java.util.*;
import java.net.*;
import static java.lang.System.out;

public class  LoreServer {
 // Vector<String> users = new Vector<String>();
  HashMap<String,HandleClient> clients = new HashMap<String,HandleClient>();

  public void process() throws Exception  {
    ServerSocket server = new ServerSocket(2046);
    out.println("Server Started...");
    while( true) {
      Socket client = server.accept();
      HandleClient c = new HandleClient(client);
      String value = c.getUserName();
  
      if( c.isPC() ) 
      {
    	  System.out.println("PC "+value+" joins" );
    	  value += "@PC";
      }
      else
      {
    	  System.out.println("MOBILE "+value+" joins" );
    	  value += "@MOBILE";
      }
      synchronized(this)
      {
    	  clients.put(value,c);
      }
     }  // end of while
  }

  public static void main(String ... args) throws Exception {
      new LoreServer().process();
  } // end of main

  public void boradcast(String user, String message)  {
    // send message to all connected users
	  synchronized(this)
      {
		  if ( clients.containsKey(user+"@PC") )
		  {
			  HandleClient c = clients.get( user+"@PC" );
			  if( c.isPC() )  
			  {
				if(c.isAlive())  
				{
					System.out.println("PC " + user + " sent " + message + " to " + " MOBILE " + user);
					c.sendMessage(user,message);
				}
				else 
				{
					System.out.println("PC " + user + " quit");
					clients.remove(user+"@PC");
				}
			  }
		  }
      }
  }

  class  HandleClient extends Thread {
        String name = "";
        BufferedReader input;
        PrintWriter output;
		boolean ifPC = false;

        public HandleClient(Socket  client) throws Exception {
          // get input and output streams
          input = new BufferedReader( new InputStreamReader( client.getInputStream())) ;
          output = new PrintWriter ( client.getOutputStream(),true);
          // read name
          String info = input.readLine();
		  String split_info[] = info.split(" ");
		  name = split_info[1];

		  if( split_info[0].equals("computer") )
		  {
          //	users.add(name); // add to vector
			ifPC = true;
		  }
          start();
        }
        

		public boolean isPC()
		{
			return ifPC;
		}

        public void sendMessage(String uname,String  msg)  {
          output.println( msg );
        }

        public String getUserName() {
          return name;
        }
        public void run()  {
          String line;
          try    {
            while(true)   {
              line = input.readLine();
              if ( line.equals("QUIT") ) {
            	  synchronized(this)
                  {
            		  if(isPC())
            		  {
            			  System.out.println("PC " + name + " quits");
            			  clients.remove(name+"@PC");
            		  }
            		  else
            		  {
            			  System.out.println("MOBILE " + name + " quits");
            			  clients.remove(name+"@MOBILE");
            		  }
            		  
                  }
              //  if( users.contains(name)) users.remove(name);
                break;
              }
              boradcast(name,line); // method  of outer class - send messages to all
            } // end of while
          } // try
          catch(Exception ex) {
            System.out.println(ex.getMessage());
          }
        } // end of run()
   } // end of inner class

} // end of Server
